package com.gaodun.scrm.common.rabbitmq.service;

import com.alibaba.fastjson.JSON;
import com.gaodun.scrm.common.rabbitmq.constant.RabbitConst;
import com.gaodun.scrm.common.rabbitmq.entity.LuffyCorrelationData;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public boolean sendMessage(String exchange, String routingKey, Object message){

        LuffyCorrelationData correlationData = new LuffyCorrelationData();
        String correlationId = UUID.randomUUID().toString();

        correlationData.setId(correlationId);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(message);

        redisTemplate.opsForValue().set(correlationId, JSON.toJSONString(correlationData),
                RabbitConst.OBJECT_TIMEOUT, TimeUnit.MINUTES);

        //未作持久化
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);
        return true;
    }

    public boolean sendDelayMessage(String exchange, String routingKey, Object message, int delayTime){

        LuffyCorrelationData correlationData = new LuffyCorrelationData();
        String correlationId = UUID.randomUUID().toString();
        correlationData.setId(correlationId);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setDelay(true);
        correlationData.setDelayTime(delayTime);

        redisTemplate.opsForValue().set(correlationId, JSON.toJSONString(correlationData),
                RabbitConst.OBJECT_TIMEOUT ,TimeUnit.MINUTES);

        rabbitTemplate.convertAndSend(exchange, routingKey, message,
                message1 -> {
                    message1.getMessageProperties().setDelay(delayTime *1000);
                    message1.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);//消息本身要做持久化
                    return message1;
                }, correlationData);

        return true;
    }


}

